package com.fsd.core.wechat.util;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class WeChatUtil {

    static String appid = "wx5f5a5d198c0627d3";
    static String secret = "bed593f312fbbb63c4e3080a8fe78e3f";

    /**
     * 通过Code获取用户关注OpenID
     */
    public static String getOpenIdByCode(String Code) throws Exception {
        String openid = "";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + Code + "&grant_type=authorization_code";
        String json = loadJson(url);
        JSONObject obj = JSONObject.fromObject(json);
        if(obj.getString("refresh_token") != null){
            String refresh_token = obj.getString("refresh_token");
            String url2 = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            String json2 = loadJson(url2);
            JSONObject obj2 = JSONObject.fromObject(json2);
            openid = obj2.getString("openid");
        }else{
            openid = obj.getString("openid");
        }
        return openid;
    }

    public static String loadJson (String url) throws Exception{
        StringBuilder json = new StringBuilder();
        URL urlObject = new URL(url);
        URLConnection uc = urlObject.openConnection();
        uc.setConnectTimeout(30000);
        uc.setReadTimeout(30000);
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
        return json.toString();
    }

    /**
     * 查看用户是否关注了该公众号
     */
    public static String getInfoByOpenid(String openid) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+getBaseToken()+"&openid="+openid+"&lang=zh_CN";
        String json = loadJson(url);
        JSONObject obj = JSONObject.fromObject(json);
        String subscribe = obj.getString("subscribe");
        return subscribe;
    }

    /**
     * 获取基础接口调用凭证
     * @return
     * @throws Exception
     */
    public static String getBaseToken() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String json = loadJson(url);
        JSONObject obj = JSONObject.fromObject(json);
        String token = obj.getString("access_token");
        return token;
    }
}
